package com.sky.controller.user;

import com.sky.constant.MessageConstant;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@Api(tags = "地址簿管理")
@RequestMapping("/user/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    @ApiOperation(value = "新增地址")
    @PostMapping
    public Result save(@RequestBody AddressBook addressBook){
        log.info("新增地址：{}", addressBook);
        addressBookService.save(addressBook);
        return Result.success();
    }

    /**
     * 查询当前登录用户的所有地址信息
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询当前登录用户的所有地址信息")
    public Result<List<AddressBook>> list(){
        List<AddressBook> list = addressBookService.list();
        log.info("查询当前登录用户的所有地址信息：{}", list);
        return Result.success(list);
    }

    /**
     * 查询默认地址
     * @return
     */
    @ApiOperation(value = "查询默认地址")
    @GetMapping("/default")
    public Result<AddressBook> getDefault(){
        AddressBook addressBook = addressBookService.getDefault();
        log.info("查询默认地址：{}", addressBook);

        if (addressBook == null){
            return Result.error(MessageConstant.NOT_DEFAULT_ADDRESS);
        }

        return Result.success(addressBook);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询地址")
    @GetMapping("/{id}")
    public Result<AddressBook> getById(@PathVariable Long id){
        log.info("根据id查询地址：{}", id);
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    /**
     * 根据id修改地址
     * @param addressBook
     * @return
     */
    @ApiOperation(value = "根据id修改地址")
    @PutMapping
    public Result update(@RequestBody AddressBook addressBook){
        log.info("修改地址：{}", addressBook);
        addressBookService.updateById(addressBook);
        return Result.success();
    }

    /**
     * 根据id删除地址
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id删除地址")
    @DeleteMapping
    public Result delete(Long id){
        log.info("删除地址：{}", id);
        addressBookService.remove(id);
        return Result.success();
    }

    /**
     * 设置默认地址
     * @return
     */
    @ApiOperation(value = "设置默认地址")
    @PutMapping("/default")
    public Result updateDefault(@RequestBody AddressBook addressBook){
        log.info("设置默认地址：{}", addressBook);
        addressBookService.updateDefault(addressBook);
        return Result.success();
    }
}